#include "stdafx.h"
#include "SamplerStateManager.h"
#include "GraphicsManager.h"


/*static*/ ID3D11Device* SamplerStateManager::device = nullptr;
/*static*/ ID3D11DeviceContext* SamplerStateManager::context = nullptr;

SamplerStateManager::SamplerStateManager(void)
{
	GraphicsManager* pGraphics = GraphicsManager::GetInstance();
	
	D3D11_SAMPLER_DESC sampler_desc;
	ZeroMemory(&sampler_desc, sizeof(D3D11_SAMPLER_DESC));
	sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_CLAMP;
	sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_CLAMP;
	sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_CLAMP;
	sampler_desc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;
	sampler_desc.MaxAnisotropy = 1;
	sampler_desc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
	sampler_desc.MinLOD = 0;
	sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;

	device->CreateSamplerState(&sampler_desc, &samplers.linearClamp);

	ZeroMemory(&sampler_desc, sizeof(D3D11_SAMPLER_DESC));

	sampler_desc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP;
	sampler_desc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP;
	sampler_desc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP;
	sampler_desc.Filter = D3D11_FILTER_ANISOTROPIC;
	sampler_desc.MaxAnisotropy = 1;
	memset(&sampler_desc.BorderColor, 0, sizeof(float) * 4);
	sampler_desc.ComparisonFunc = D3D11_COMPARISON_LESS_EQUAL;
	sampler_desc.MinLOD = 0;
	sampler_desc.MaxLOD = D3D11_FLOAT32_MAX;

	device->CreateSamplerState(&sampler_desc, &samplers.linearWrap);
}

SamplerStateManager::~SamplerStateManager(void)
{
	samplers.linearClamp->Release();
	samplers.linearWrap->Release();
}

SamplerState* SamplerStateManager::getCurrentSamplerState(unsigned int slotIndex) const
{
	SamplerState* outval;
	GraphicsManager::GetInstance()->getDeviceContext()->PSGetSamplers(slotIndex, 1, &outval);
	return outval;
}

void SamplerStateManager::setCurrentSamplerState(SamplerState* state, PiplineIndex slotIndex)
{
	if (slotIndex.slot == ALL_TEXTURE_SLOTS)
	{
		SamplerState* samplers[8] =
		{
			state, state, state, state,
			state, state, state, state,
		};

		switch (slotIndex.shader_index)
		{
		case SHADER_INDEX_PIXEL_SHADER:
			context->PSSetSamplers(0, 8, samplers);
			break;
		case SHADER_INDEX_VERTEX_SHADER:
			context->VSSetSamplers(0, 8, samplers);
			break;
		case SHADER_INDEX_GEOMETRY_SHADER:
			context->VSSetSamplers(0, 8, samplers);
			break;
		}
	}
	else
	{

		switch (slotIndex.shader_index)
		{
		case SHADER_INDEX_PIXEL_SHADER:
			context->PSSetSamplers(0, 1, &state);
			break;
		case SHADER_INDEX_VERTEX_SHADER:
			context->VSSetSamplers(0, 1, &state);
			break;
		case SHADER_INDEX_GEOMETRY_SHADER:
			context->GSSetSamplers(0, 1, &state);
			break;
		}
	}
}